package controllers;

import models.User;
import play.libs.F.Promise;
import play.libs.WS;
import play.mvc.Controller;
import play.mvc.Result;
import services.UserService;
import util.UserSession;
import exceptions.NoUUIDException;

public class Calendaryou extends Controller{
	public static final UserService userService = UserService.getInstance();

	public static Result linkCallback(Long cid, Boolean success){
		try {
			UserSession userSession = userService.getUserSession(session());

			// If filyou redirect returned a success message
			if(success){
				//TODO tratar para funcionar direito pegando o id da sessão. Atualmente ele dá nullpointer em condições desconhecidas :/
				//User user = (User) JPA.em().createQuery("FROM User u WHERE u.filyouId = :id").setParameter("id", userSession.getUser().getFilyouId()).getSingleResult();
				User user = User.finder.where().eq("calendaryouId", cid).findUnique();
				user.calendaryouLinked = true;
				user.save();
				userSession.setUser(user);// update user in memory
				// update user from cache
				userService.updateExistingUserSession(userSession);

				return redirect(routes.Connect.index());
			}

			return badRequest();
		} catch (NoUUIDException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		return redirect(routes.Connect.index());
	}

	public static Result unlink(Long cid){
		try {
			UserSession userSession = userService.getUserSession(session());

			// Try to unlink account on emaiyou server
			// TODO extract the necessary operations from calendaryou to avoid this hack
			Promise<WS.Response> result = WS.url(
					collectors.calendar.controllers.routes.Application.unlink(
							cid).absoluteURL(request())).get();

			// If the HTTP STATUS is 200 than account is unlinked
			if(result.get(10000l).getStatus() == 200 && userSession.getUser().calendaryouId.equals(cid)){
				// Get a user from database. Necessary for persistence. For this to word this method should be annotated with @play.db.jpa.Transactional
				User user = User.finder.where().eq("calendaryouId", cid).findUnique();
				user.calendaryouLinked = false; // update link status
				user.save();
				userSession.setUser(user);// update user in memory
				// update user from cache
				userService.updateExistingUserSession(userSession);
				
				return redirect(routes.Connect.index());
			}else{
				badRequest("Error trying to unlink FilYOU");
			}
		} catch (NoUUIDException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		return redirect(routes.Connect.index());
	}

}
